#coding:utf-8
#__author:PC  
#date: 2022/1/11
import requests,re,execjs
import hashlib,json

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
    'Host': 'www.mps.gov.cn',
    'Accept-Language': 'zh-CN,zh;q=0.9'
}
two_url = 'https://www.mps.gov.cn/n2254098/n4904352/c8321709/content.html'

def _hash(val: str, hash_name: str):
    """hash方法"""
    hash_func = getattr(hashlib, hash_name)
    return hash_func(val.encode()).hexdigest()

def get_jsl_clearance(ct, bts, chars, hash_name):
    """加速乐cookie加密逻辑"""
    chars_len = len(chars)
    for i in range(chars_len):
        for j in range(chars_len):
            # print(i,j)
            jsl_clearance = bts[0] + chars[i] + chars[j] + bts[1]
            # print(jsl_clearance)
            # print(ct)
            if _hash(jsl_clearance, hash_name) == ct:
                return jsl_clearance

def first_resq():
    url = 'http://www.mps.gov.cn/'
    response = requests.get(url, headers=headers, timeout=5)
    print(response)
    print(response.text)
    clearance = re.findall('<script>document.cookie=(.*);', response.text)[0]
    __jsl_clearance = execjs.eval(clearance).replace('__jsl_clearance', '__jsl_clearance_s')
    print(f'__jsl_clearance:{__jsl_clearance}')
    __jsluid_h = response.headers['Set-Cookie'].split(';')[0].replace('__jsluid_h', '__jsluid_s')
    cookie_one = f'{__jsluid_h}; {__jsl_clearance}'
    print(f'第一次Cookie:{cookie_one}')
    return cookie_one,__jsl_clearance

def two_resq(cookie_one,two_url,__jsl_clearance):

    headers['Cookie'] = cookie_one
    two_resp = requests.get(two_url, headers=headers, timeout=5)
    print(two_resp.text)
    resp_dict = re.findall(';go\((.*)\)</script>', two_resp.text)[0]
    print(resp_dict)
    resp_json = json.loads(resp_dict)
    result = get_jsl_clearance(resp_json['ct'], resp_json['bts'], resp_json['chars'], resp_json['ha'])
    print(f'第二次get_jsl_clearance:{result}')
    cookie_two = cookie_one.replace(__jsl_clearance, f'__jsl_clearance_s={result}')
    print(f'第二次Cookie:{cookie_two}')
    return cookie_two

def three_resq(cookie_two):
    headers['Cookie'] = cookie_two

    three_resp = requests.get(two_url, headers=headers, timeout=5)
    print(three_resp)
    print(three_resp.encoding)  # ISO-8859-1
    three_resp.encoding = 'utf-8'
    print(three_resp.text)

cookie_one,__jsl_clearance = first_resq()

cookie_two = two_resq(cookie_one,two_url,__jsl_clearance)

three_resq(cookie_two)
